import { reactive, watch } from 'vue'

import { getMetaDataState } from './state/state-meta-data'

// 定义表单需要的 meta
const formMeta = reactive({
  formMeta: {
    moduleId: 142,
    formId: 14210,
    columnsNumber: 2,
    colOrder: [],
    linkageMeta: {},
    ruleMeta:{},
    subMeta:{
      type: 'card',
      cardColCount: 1,
      cols: [
        {
          title: "分组一",
          colIds: []
        }
      ]
    }
  },
  itemMeta: {}
})

// 字段单独的meta
const colMeta = reactive({})

const getType = (type, type2) => {
  switch(type) {
    case 'datetime':
      return 120
    case 'int':
      return 110
    default:
      return type2
  }
}

/**
 * 重置 model
 * @param cols 
 * @param model 
 */
const resetModel = (cols, model) => {
  // 清空
  for(const key in model) {
    delete model[key]
  }
  cols.forEach(col => {
    switch(col.defaultValue) {
      case 'getdate()':
        model[col.colName] = dayjs(new Date()).format('YYYY-MM-DD')
        break;
      default:
        model[col.colName] = col.defaultValue
        break;
    }
    switch(col.controlTypeId.toString()) {
      case '125':
      case '126':
      case '127':
      case '128':
      case '131':
      case '152':
      case '161':
      case '163':
      case '166':
        model[col.colName] = []
        break;
      case '108':
      case '120':
      case '121':
      case '122':
      case '123':
      case '124':
        model[col.colName] = ''
        break;
      case '110':
      case '111':
      case '112':
        model[col.colName] = 0
        break;
      
    }
  })
}

/**
 * 设置 meta
 * @param cols 
 * @param model 
 */
const _toMetaCol = (cols) => {
  // 清空
  for(const key in colMeta) {
    delete colMeta[key]
    delete formMeta.itemMeta[key]
  }
  formMeta.formMeta.colOrder.length = 0

  // 遍历
  cols.forEach(col => {
    const meta = {
      formItemMeta: {
        columnId: col.columnId,
        colName: col.colName,
        label: col.cnName,
        controlType: col.controlTypeId, //getType(col.colType, col.controlTypeId),
        isClear: false,
        defValue: col.defaultValue,
        colCount: 1
      },
      placeholder: '请填写' + col.cnName,
      title: col.cnName
    }
    colMeta[col.columnId] = meta
    formMeta.itemMeta[col.columnId] = meta
    formMeta.formMeta.colOrder.push(col.columnId)
  })
}


/**
 * 创建字段的 meta
 */
export const toMetaForm = (model) => {
  const state = getMetaDataState()
  // const { sheetNames, current } = state
 
  watch(state.current.table.cols, (cols) => {
    resetModel(cols, model)
    clearTimeout(state.timeoutForm)
    state.timeoutForm = setTimeout(() => {
      _toMetaCol(cols)
    }, 130)
  })

  return {
    formMeta,
    colMeta
  }
}